<?php
/**
 * 娱乐信息控制器
 * User: sunlight
 * Date: 2018/11/19
 * Time: 16:21
 */

namespace app\admin\controller;

use think\Exception;

class Product extends BaseController{

    public function index(){
        $data=input('param.');
        $query=http_build_query($data);
        $whereData = [];
        //转换查询调教
        if (!empty($data['start_time']) && !empty($data['end_time'])
            && $data['end_time'] > $data['start_time']){
            $whereData['create_time'] = [
                ['gt',strtotime($data['start_time'])],
                ['lt',strtotime($data['end_time'])]
            ];
        }

        if (!empty($data['catid'])){
            $whereData['catid'] = intval($data['catid']);
        }

        if (!empty($data['address'])){
            $whereData['address'] = intval($data['address']);
        }

        if(!empty($data['title'])) {
            $whereData['title'] = ['like', '%'.$data['title'].'%'];
        }

        //获取数据，然后填充到模板中
        $this->getPageAndSize($data);

        $m=model('Product');

        //获取数据库表数据
        $product=$m->getProductByCondition($whereData, $this->from, $this->size);

        //获取满足条件的数据总数=》有多少页
        $total=$m->getProductCountByCondition($whereData);
        // 结合总数+size  =》 有多少页
        $pageTotal = ceil($total/$this->size);//1.1 =>2

        return $this->fetch('',[
            'cat' => config('cat.lists'),
            'address'=>config('address.addresslists'),
            'product' => $product,
            'pageTotal' => $pageTotal,
            'curr' => $this->page,
            'start_time' => empty($data['start_time'])?'':$data['start_time'],
            'end_time' => empty($data['end_time']) ? '' : $data['end_time'],
            'catid' => empty($data['catid']) ? '' : $data['catid'],
            'adds' => empty($data['address']) ? '' : $data['address'],
            'title' => empty($data['title']) ? '' : $data['title'],
            'query' => $query
        ]);
    }

    public function add(){
        if (request()->isPost()){
            $data=input('post.');
            //入库操作
            try{
                $id=model('Product')->add($data);
            }catch (Exception $e){
                return $this->result('', 0, '新增失败');
            }

            if ($id){
                return $this->result(['jump_url' => url('Product/index')], 1, 'OK');
            }else{
                return $this->result('', 0, '新增失败');
            }
        }else{
            return $this->fetch('',[
                'cat'=>config('cat.lists'),
                'address'=>config('address.addresslists'),
            ]);
        }
    }

}